﻿using ShareFrame.Api.Extentions;
using ShareFrame.Util;
using EFCore.Sharding;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NSwag;
using System.Linq;

namespace ShareFrame.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        private readonly IConfiguration _configuration;


        /// <summary>
        /// 加载配置服务
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<ApiBehaviorOptions>(options => options.SuppressModelStateInvalidFilter = true);
            services.AddControllers(options =>
            {
                options.Filters.Add<ValidFilterAttribute>();
                options.Filters.Add<GlobalExceptionFilter>();
            })
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.GetType().GetProperties().ForEach(aProperty =>
                {
                    var value = aProperty.GetValue(JsonExtention.DefaultJsonSetting);
                    aProperty.SetValue(options.SerializerSettings, value);
                });
            });
            services.AddHttpContextAccessor();

            #region Swagger分组说明配置信息
            //登录管理
            services.AddOpenApiDocument(settings =>
            {
                settings.AllowReferencesWithProperties = true;
                settings.DocumentName = "主页登录及测试";
                settings.Version = "v1";
                settings.Title = "ShareFrame项目接口文档";
                settings.Description = "ShareFrame项目用户登录接口说明";
                settings.ApiGroupNames = new string[] { "主页登录及测试" };
                settings.PostProcess = document =>
                {
                    document.Info.Contact = new OpenApiContact()
                    {
                        Name = "DongChen",
                        Email = "18810573293@163.com",
                        Url = null
                    };
                };
                settings.AddSecurity("身份认证Token", Enumerable.Empty<string>(), new OpenApiSecurityScheme()
                {
                    Scheme = "bearer",
                    Description = "<b>Authorization：JWT授权(数据将在请求头中进行传输) 直接在下框中输入{your JWT token}</b><br/><b>授权地址：/Base_Manage/Home/SubmitLogin</b>",
                    Name = "Authorization",
                    In = OpenApiSecurityApiKeyLocation.Header,
                    Type = OpenApiSecuritySchemeType.Http
                });
            });
            //数据管理
            services.AddOpenApiDocument(settings =>
            {
                settings.AllowReferencesWithProperties = true;
                settings.DocumentName = "数据管理";
                settings.Version = "v1";
                settings.Title = "ShareFrame项目接口文档";
                settings.Description = "ShareFrame项目基础档案管理接口说明";
                settings.ApiGroupNames = new string[] { "基础档案管理" };
                settings.PostProcess = document =>
                {
                    document.Info.Contact = new OpenApiContact()
                    {
                        Name = "DongChen",
                        Email = "18810573293@163.com",
                        Url = null
                    };
                };
                settings.AddSecurity("身份认证Token", Enumerable.Empty<string>(), new OpenApiSecurityScheme()
                {
                    Scheme = "bearer",
                    Description = "<b>Authorization：JWT授权(数据将在请求头中进行传输) 直接在下框中输入{your JWT token}</b><br/><b>授权地址：/Base_Manage/Home/SubmitLogin</b>",
                    Name = "Authorization",
                    In = OpenApiSecurityApiKeyLocation.Header,
                    Type = OpenApiSecuritySchemeType.Http
                });
            });
            //系统管理
            services.AddOpenApiDocument(settings =>
            {
                settings.AllowReferencesWithProperties = true;
                settings.DocumentName = "系统管理";
                settings.Version = "v1";
                settings.Title = "ShareFrame项目接口文档";
                settings.Description = "ShareFrame项目系统管理接口说明";
                settings.ApiGroupNames = new string[] { "系统管理" };
                settings.PostProcess = document =>
                {
                    document.Info.Contact = new OpenApiContact()
                    {
                        Name = "DongChen",
                        Email = "18810573293@163.com",
                        Url = null
                    };
                };
                settings.AddSecurity("身份认证Token", Enumerable.Empty<string>(), new OpenApiSecurityScheme()
                {
                    Scheme = "bearer",
                    Description = "<b>Authorization：JWT授权(数据将在请求头中进行传输) 直接在下框中输入{your JWT token}</b><br/><b>授权地址：/Base_Manage/Home/SubmitLogin</b>",
                    Name = "Authorization",
                    In = OpenApiSecurityApiKeyLocation.Header,
                    Type = OpenApiSecuritySchemeType.Http
                });
            });
            //配置管理
            services.AddOpenApiDocument(settings =>
            {
                settings.AllowReferencesWithProperties = true;
                settings.DocumentName = "配置管理";
                settings.Version = "v1";
                settings.Title = "ShareFrame项目接口文档";
                settings.Description = "ShareFrame项目配置管理接口说明";
                settings.ApiGroupNames = new string[] { "配置管理" };
                settings.PostProcess = document =>
                {
                    document.Info.Contact = new OpenApiContact()
                    {
                        Name = "DongChen",
                        Email = "18810573293@163.com",
                        Url = null
                    };
                };
                settings.AddSecurity("身份认证Token", Enumerable.Empty<string>(), new OpenApiSecurityScheme()
                {
                    Scheme = "bearer",
                    Description = "<b>Authorization：JWT授权(数据将在请求头中进行传输) 直接在下框中输入{your JWT token}</b><br/><b>授权地址：/Base_Manage/Home/SubmitLogin</b>",
                    Name = "Authorization",
                    In = OpenApiSecurityApiKeyLocation.Header,
                    Type = OpenApiSecuritySchemeType.Http
                });
            });
            //配置管理
            services.AddOpenApiDocument(settings =>
            {
                settings.AllowReferencesWithProperties = true;
                settings.DocumentName = "未分组接口";
                settings.Version = "v1";
                settings.Title = "ShareFrame项目接口文档";
                settings.Description = "ShareFrame项目未分组接口说明";
                settings.ApiGroupNames = new string[] { "未分组接口" };
                settings.PostProcess = document =>
                {
                    document.Info.Contact = new OpenApiContact()
                    {
                        Name = "DongChen",
                        Email = "18810573293@163.com",
                        Url = null
                    };
                };
                settings.AddSecurity("身份认证Token", Enumerable.Empty<string>(), new OpenApiSecurityScheme()
                {
                    Scheme = "bearer",
                    Description = "<b>Authorization：JWT授权(数据将在请求头中进行传输) 直接在下框中输入{your JWT token}</b><br/><b>授权地址：/Base_Manage/Home/SubmitLogin</b>",
                    Name = "Authorization",
                    In = OpenApiSecurityApiKeyLocation.Header,
                    Type = OpenApiSecuritySchemeType.Http
                });
            });
            #endregion

            //jwt
            services.AddJwt(_configuration);
            //加载MongoDB|WxMiniAppConfig|Dapper
            services.AddSetting(_configuration);
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //跨域
            app.UseCors(x =>
                {
                    x.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .DisallowCredentials();
                })
                .UseForwardedHeaders(new ForwardedHeadersOptions
                {
                    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
                })
                .UseMiddleware<RequestBodyMiddleware>()
                .UseMiddleware<RequestLogMiddleware>()
                .UseDeveloperExceptionPage()
                .UseStaticFiles(new StaticFileOptions
                {
                    ServeUnknownFileTypes = true,
                    DefaultContentType = "application/octet-stream"
                })
                .UseRouting()
                .UseAuthentication()
                .UseAuthorization()
                .UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers().RequireAuthorization();
                })
                .UseOpenApi()
                .UseSwaggerUi3()//添加Swagger UI到请求管道中(默认路由: /swagger).
            ;
        }
    }
}
